/*
 * Copyright (C) 2012  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.swing.util;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.EventListener;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

import javax.swing.Action;

import nemos.util.osgi.BundleClassLoader;

import org.osgi.framework.BundleContext;

/**
 * ListenerAdapter : The swing listeners adapter.
 * 
 * @author Romain DUBOIS
 */
public class ListenerAdapter extends ActionFinder implements InvocationHandler {

    /**
     * Get a listener linked to the appropriate actions.
     * 
     * @param pContext
     *            The bundle context
     * @param pIntf
     *            The listener interface
     * @param pParams
     *            The listener parameters
     * @param pPrefix
     *            The prefix of listener methods
     * @return The listener instance
     */
    public static <T extends EventListener> T getListener(final BundleContext pContext,
            final Class<T> pIntf, final Map<String, ?> pParams, final String pPrefix) {
        final ListenerAdapter lAdapter = new ListenerAdapter(pContext);
        lAdapter.addListener(pIntf, pParams, pPrefix);

        final ClassLoader lLoader = new BundleClassLoader(pContext.getBundle());
        return pIntf.cast(Proxy.newProxyInstance(lLoader, new Class<?>[] { pIntf }, lAdapter));
    }

    /**
     * Get a listener linked to the appropriate actions.
     * 
     * @param pContext
     *            The bundle context
     * @param pIntf
     *            The listener interface
     * @param pParams
     *            The listener parameters
     * @return The listener instance
     */
    public static <T extends EventListener> T getListener(final BundleContext pContext,
            final Class<T> pIntf, final Map<String, ?> pParams) {
        return getListener(pContext, pIntf, pParams, ""); //$NON-NLS-1$
    }

    /** The name map */
    private final Map<Method, String> mNames;
    /** The actions map */
    private final Map<String, Action> mActions;

    /**
     * Constructor.
     * 
     * @param pContext
     *            The bundle context
     */
    public ListenerAdapter(final BundleContext pContext) {
        super(pContext);

        mNames = new HashMap<Method, String>();
        mActions = new HashMap<String, Action>();
    }

    /**
     * Add a listener to the adapter.
     * 
     * @param pIntf
     *            The new supported type
     * @param pParams
     *            The adaptation parameters
     * @param pPrefix
     *            The methods prefix
     */
    public void addListener(final Class<? extends EventListener> pIntf,
            final Map<String, ?> pParams, final String pPrefix) {

        for (final Method lMethod : pIntf.getMethods()) {

            // Resolve method name
            String lName = lMethod.getName();
            if (pPrefix != null) {
                if (lName.startsWith(pPrefix)) {
                    // Remove prefix and lower the first character
                    lName = lName.substring(pPrefix.length());
                    lName = lName.toLowerCase().charAt(0) + lName.substring(1);
                } else {
                    // Skip unhandled method
                    continue;
                }
            }

            // Find the associated action
            Action lAction = null;
            final String lActionName = (String) pParams.get(lName);
            if (lActionName != null) {
                lAction = findAction(lActionName);
            }

            // Store result
            if (lAction != null) {
                mNames.put(lMethod, lName);
                mActions.put(lName, lAction);
            }
        }
    }

    /**
     * {@inheritDoc}
     * 
     * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
     *      java.lang.reflect.Method, java.lang.Object[])
     */
    @Override
    public Object invoke(@SuppressWarnings("unused") final Object pProxy, final Method pMethod,
            final Object[] pArgs) {

        final String lActionName = mNames.get(pMethod);
        final Action lAction = mActions.get(lActionName);
        if (lAction != null && lAction.isEnabled()) {

            // Find the source event
            EventObject lSrcEvent = null;
            InputEvent lSrcInputEvent = null;
            for (final Object lArg : pArgs) {
                if (lArg instanceof InputEvent) {
                    lSrcInputEvent = (InputEvent) lArg;
                    lSrcEvent = lSrcInputEvent;
                    break;
                }
                if (lSrcEvent == null && lArg instanceof EventObject) {
                    lSrcEvent = (EventObject) lArg;
                }
            }

            // Prepare event to send
            Object lSrc = null;
            final int lId = ActionEvent.ACTION_PERFORMED;
            int lModifiers = 0;
            long lWhen = 0L;

            // Source event is an input event
            if (lSrcInputEvent != null) {
                lModifiers = lSrcInputEvent.getModifiers();
                lWhen = lSrcInputEvent.getWhen();
            }

            // Generic event found
            if (lSrcEvent != null) {
                lSrc = lSrcEvent.getSource();
            }

            // Call the action
            lAction.actionPerformed(new ActionEvent(lSrc, lId, lActionName, lWhen, lModifiers));
        }
        return null;
    }
}
